package me.jiatao.paging3.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState
import kotlinx.coroutines.delay
import me.jiatao.paging3.network.pojo.ArticleItem
import me.jiatao.paging3.network.retrofit.HttpConst
import me.jiatao.paging3.network.retrofit.RetrofitClient
import me.jiatao.paging3.network.retrofit.apiCall

class ProjectPagingSource : PagingSource<Int, ArticleItem>() {
    private val SHOE_START_INDEX = 1

    /**
     * 实现这个方法来触发异步加载(例如从数据库或网络)。 这是一个suspend挂起函数，可以很方便的使用协程异步加载
     */
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleItem> {
        val pos = params.key ?: SHOE_START_INDEX
        //val startIndex = pos * params.loadSize + 1
        //val endIndex = (pos + 1) * params.loadSize

        if (pos == 5) {
            delay(1000)
            return LoadResult.Error(Exception("没有数据了"))
        }

        /**
         * 执行网络请求
         */
        val projectResult = apiCall {
            RetrofitClient.wanAndroidApi.getProjectList(pos)
        }

        if (projectResult.code == HttpConst.CODE_SUCCESS) {
            projectResult.data?.let { projectData ->
                projectData.datas?.let {
                    return LoadResult.Page(
                        it,
                        if (pos <= SHOE_START_INDEX) null else pos - 1,
                        if (it.isNullOrEmpty()) null else pos + 1
                    )
                }
            }
            return LoadResult.Error(Exception("数据为空"))

        } else {
            return LoadResult.Error(Exception(projectResult.message))
        }
    }

    override fun getRefreshKey(state: PagingState<Int, ArticleItem>): Int? {
        println("getRefreshKey")
        return state.anchorPosition

        //return state.anchorPosition?.let { anchorPosition ->
        //    state.pages[anchorPosition].nextKey
        //}
    }
}